package com.shopping.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shopping.impl.ShoppingCart;
import com.shopping.vo.CartItem;
import com.tools.StringUtil;

public class AddShoppingCartServlet extends HttpServlet {

	private static final long serialVersionUID = 2160627295681168230L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingcart");
		if (cart == null) {
			cart = new ShoppingCart();
			session.setAttribute("shoppingcart", cart);
		}
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String price = request.getParameter("price");

		if (StringUtil.validateIsNull(id) || StringUtil.validateIsNull(name)
				|| StringUtil.validateIsNull(price)) {
			printError(request, response);
			return;
		}
		CartItem item = new CartItem();
		item.setId(id);
		item.setName(name);
		item.setQuantity(1);
		try {
			item.setPrice(Double.parseDouble(price));
			cart.addCartItem(item);
		} catch (NumberFormatException e) {
			printError(request, response);
			return;
		}
		response.sendRedirect("/test/getShoppingCart");
	}

	public void printError(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head><title>add shoppingCartItem</title></head>");
		out.println("<body>");
		out.println("<h2>添加商品到购物车，请重新添加商品</h2><br><br>");
		out.println("<a href='/test/displayItems.html'>添加商品</a><br><br>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
